//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package com.yami.shop.common.util.pdfUtil;

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.*;

import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ObjectUtils;

public class PdfUtils {
    private static final String templatePath = "pdf/";
    private static Logger logger = LoggerFactory.getLogger(PdfUtils.class);
    private static BaseFont BASE_FONT = null;
    private static ArrayList<BaseFont> FONT_LIST = new ArrayList();

    public PdfUtils() {
    }


    public static void generatePdf(String template, OutputStream output, Map<String, Object> data) {
        try {
            String templateFilePath = "pdf/" + template;
            InputStream is = PdfUtils.class.getClassLoader().getResourceAsStream(templateFilePath);
            generatePdf(is, output, data,null,85f);
            is.close();
        } catch (Exception var5) {
            logger.error("模板文件'" + template + "'读取失败", var5);
        }
    }

    public static void generatePdf(InputStream template, OutputStream output, Map<String, Object> data, Map<String, String> imageMap,float textFont)  {
        PdfReader reader = null;

        try {
            reader = new PdfReader(template);
        } catch (IOException var17) {
            logger.error(var17.getMessage(), var17);
        }

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        PdfStamper ps = null;

        try {
            ps = new PdfStamper(reader, bos);
        } catch (IOException | DocumentException var15) {
            logger.error(var15.getMessage(), var15);
        } finally {
            ;
        }

        ps.getUnderContent(1);
        AcroFields fields = ps.getAcroFields();
        fields.setSubstitutionFonts(FONT_LIST);
        // 补充字体
        fillData(fields, data,textFont);
        // 补充图片
        insertImage(fields,ps,imageMap);

        ps.setFormFlattening(true);

        try {
            ps.close();
        } catch (IOException | DocumentException var14) {
            logger.error(var14.getMessage(), var14);
        }

        try {
            output.write(bos.toByteArray());
            output.flush();
            bos.close();
            reader.close();
        } catch (IOException var13) {
            logger.error(var13.getMessage(), var13);
        }

    }

    private static void insertImage(AcroFields form, PdfStamper stamper,Map<String,String> imageMap) {
        if (imageMap != null && !imageMap.isEmpty()) {
            for(String key:imageMap.keySet()){
                int pageNo = form.getFieldPositions(key).get(0).page;
                Rectangle signRect = form.getFieldPositions(key).get(0).position;
                float x = signRect.getLeft();
                float y = signRect.getBottom();
                try {
                    Image image = Image.getInstance(imageMap.get(key));
                    // 获取操作的页面
                    PdfContentByte under = stamper.getOverContent(pageNo);
                    // 根据域的大小缩放图片
                    image.scaleToFit(signRect.getWidth(), signRect.getHeight());
                    // 添加图片
                    image.setAbsolutePosition(x, y);
                    under.addImage(image);
                } catch (Exception e) {
                    logger.error("插入图片异常");
                    e.printStackTrace();
                }
            }

        }

    }

    private static void fillData(AcroFields fields, Map<String, Object> data, float textFont) {
        if (data != null && !data.isEmpty()) {
            for (String key : data.keySet()) {
                String value = ObjectUtils.getDisplayString(data.get(key));

                try {
                    fields.setFieldProperty(key, "textsize", textFont, null);
//                    fields.setFieldProperty(key, "textcolor", BaseColor.RED, null);
//                    fields.setFieldProperty(key, "textfont", BaseFont.createFont(BaseFont.HELVETICA_BOLD, BaseFont.WINANSI, BaseFont.EMBEDDED), null);
                    fields.setField(key, value);
                } catch (DocumentException | IOException var6) {
                    logger.error(var6.getMessage(), var6);
                }
            }
        }

    }

    static {
        try {
//            InputStream is = PdfUtils.class.getClassLoader().getResourceAsStream("font/STZHONGS.TTF");
//            BASE_FONT = Font.createFont(Font.TRUETYPE_FONT, is);
            BASE_FONT = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", false);
        } catch (IOException | DocumentException var1) {
            logger.error(var1.getMessage(), var1);
        }

        FONT_LIST.add(BASE_FONT);
    }
}
